<?php

//------------------------
// 后台用户控制器
//-------------------------
namespace app\admin\controller;

use app\common\controller\AdminBase;
use app\common\model\AdminUser as AdminUserModel;
use app\common\model\AuthGroupAccess as AuthGroupAccessModel;
use think\Config;
use think\Db;

class AdminUser extends AdminBase
{
    protected $AdminUserModel;
    protected $AuthGroupAccessModel;

    protected function _initialize()
    {
        parent::_initialize();
        $this->AdminUserModel       = new AdminUserModel();
        $this->AuthGroupAccessModel = new AuthGroupAccessModel();
    }


    // 用户列表
    public function index(){
        $username    = $this->request->param('username','','trim');
        $status      = $this->request->param('status',0,'intval');
        $is_delete   = $this->request->param('is_delete',0,'intval');
        $start       = $this->request->param('start','','trim');
        $stop        = $this->request->param('stop','','trim');

        $where = array();
        if ($status) {
            $_status = $status == 2?0:1;
            $where['status'] = array('eq',$_status);
        }
        if ($is_delete) {
            $_is_delete = $is_delete == 2?0:1;
            $where['is_delete'] = array('eq',$_is_delete);
        }
        if ($username) {
             $where['username'] = array('like','%'.$username.'%');
        }
        //日期搜索
        if ($start) {
            $_start = strtotime(date('Y-m-d 00:00:00', strtotime($start)));
            $where['last_login_time'] = array('egt',$_start);
        }
        if ($stop) {
            $_stop  = strtotime(date('Y-m-d 23:59:59', strtotime($stop)));
            $where['last_login_time'] = array('elt',$_stop);
        }
        if ($start && $stop) {
            $_start = strtotime(date('Y-m-d 00:00:00', strtotime($start)));
            $_stop  = strtotime(date('Y-m-d 23:59:59', strtotime($stop)));
            if ($_start > $_stop) {
                $_stop = $_start + 86400;
            }
            $where['last_login_time'] = array('between',array($_start,$_stop));
        }

        $info = $this->AdminUserModel->where($where)->
          paginate(10,false,['query' => [
            'status'    =>$status,
            'is_delete' =>$is_delete,
            'start'     =>$start,
            'stop'      =>$stop,
            'username'  =>$username
            ] ]);

        $this->assign('username',$username);
        $this->assign('status',$status);
        $this->assign('is_delete',$is_delete);
        $this->assign('start',$start);
        $this->assign('stop',$stop);
        $this->assign('info',$info);

        return $this->fetch('index');
    }


    // 添加页面
    function add(){
        return $this->fetch('add');
    }

    /**
     * @desc 添加操作
     */
    public function addProc() {
        $data            = $this->request->param();
        //使用AdminUser验证器的add场景
        $validate_result = $this->validate($data, 'AdminUser.add');

        if ($validate_result !== true) {
                $this->error($validate_result);
        }

        $now = time();
        $addData = array(
            'username'        => $data['username'],
            'password'        => user_encryption($data['password']),
            'status'          => $data['status'],
            'is_delete'        => $data['is_delete'],
            'create_time'     => $now,
            'last_login_time' => $now
        );

        $res = $this->AdminUserModel->save($addData);

        if ($res === false) {
            $this->error($this->AdminUserModel->getError());
        } else {
            $this->success('添加成功');
        }
    }

    // 编辑页面
    function edit(){
        $id = $this->request->param('id',0,'intval');

        $data = $this->AdminUserModel->get($id);

        $this->assign('data',$data);
        return $this->fetch('edit');
    }

    // 编辑操作
    function editProc(){
        $data  = $this->request->param('');
        $scene = $this->request->param('scene','','trim');
        $data['update_time'] = time();

        //根据传入的scene生成不同的场景
        $validate_result = $this->validate($data, 'AdminUser.'.$scene);

        if ($validate_result !== true) {
                $this->error($validate_result);
        }

        // 如果场景是编辑密码，需要特殊验证和密码加密处理
        if ($scene == 'editPassword') {
            if (!check_password($data['old_password'],$data['id'])) {
                $this->error('旧密码输入有误');
            }

            $data['password'] = user_encryption($data['password']);
        }

        // allowField表示过滤非数据表中字段的数据
        $res = $this->AdminUserModel->allowField(true)->save($data,$data['id']);

        if ($res === false) {
            $this->error($this->AdminUserModel->getError());
        } else {
            $this->success('保存成功');
        }
    }



    // 删除操作
    public function delete(){
        $id = $this->request->param('id',0,'intval');

        if ($id == 1) {
           $this->error('超级管理员不能删除');
        }

        $where['is_delete'] = array('eq',1);
        $where['id'] = array('eq',$id);

        $res = $this->AdminUserModel->where($where)->delete();

        if ($res === false) {
            $this->error($this->AdminUserModel->getError());
        } else{
            // 删除成功后，才删除中间表的数据
            if ($res != 0) {
                $this->AuthGroupAccessModel->where('uid',$id)->delete();
                $this->success('删除成功');
            } else {
                $this->error('该用户不能删除');
            }

        }
    }

    // 用户详情
    public function detail(){
        $id = $this->request->param('id',0,'intval');

        $data = $this->AdminUserModel->get($id);
        $groups = model('UserGroupView')->where('platform_auth_group_access.uid',$id)->select();
// halt($groups);
        $this->assign('groups',$groups);
        $this->assign('data',$data);
        return $this->fetch('detail');
    }



    // 批量删除用户>>调用
    private function _batchDelete($id){
        $where['is_delete'] = array('eq',1);
        $where['id'] = array('eq',$id);
        $res = $this->AdminUserModel->where($where)->delete();

        if ($res == false) {
           return false;
        } else {
            $this->AuthGroupAccessModel->where('uid',$id)->delete();
            return true;
        }

    }


    // 批量处理
    public function batchProc(){
        $data = $this->request->param();

        $ids = implode(',',$data['ids']);
        $map['id']  = ['in',$ids];
        $type = $data['type'];

        switch ($type) {
            case 'delete':
                $successData = array();
                $failData = array();
                for ($i=0; $i < count($data['ids']); $i++) { 
                    $result = $this->_batchDelete($data['ids'][$i]);
                    if ($result) {
                        array_push($successData, $data['ids'][$i]);
                    } else {
                        array_push($failData, $data['ids'][$i]);
                    }
                }
                $success = implode(',',$successData);
                $fail   = implode(',',$failData);
                $this->success('删除成功id为：'.$success.'，删除失败id为：'.$fail);
                break;
            case 'disable':
                $res = $this->AdminUserModel->where($map)->update(['status' => '0']);
                $act = '禁用';
                break;
            case 'enable':
                $res = $this->AdminUserModel->where($map)->update(['status' => '1']);
                $act = '启用';
                break;

            default:
                $this->error('非法操作');
                break;
        }

        if ($res === false) {
            $this->error($this->AdminUserModel->getError());
        } else {
            $this->success('批量'.$act.'成功');
        }

    }




}